---
import I18nKey from "../i18n/i18nKey";
import { i18n } from "../i18n/translation";

export interface Props {
	encryptedContent: string;
	passwordHash: string;
}

const { encryptedContent, passwordHash } = Astro.props;
---

<div id="password-protection" class="password-protection">
  <div class="password-container">
    <div class="lock-icon">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6z" fill="currentColor"/>
      </svg>
    </div>
    <h2>{i18n(I18nKey.passwordProtectedTitle)}</h2>
    <p>{i18n(I18nKey.passwordProtectedDescription)}</p>
    <div class="password-input-group">
      <input 
        type="password" 
        id="password-input" 
        placeholder={i18n(I18nKey.passwordPlaceholder)}
        class="password-input"
      />
      <button id="unlock-btn" class="unlock-button">{i18n(I18nKey.passwordUnlock)}</button>
    </div>
    <div id="error-message" class="error-message" style="display: none;">{i18n(I18nKey.passwordIncorrect)}</div>
  </div>
</div>

<div id="decrypted-content" class="decrypted-content" style="display: none;"></div>

<style>
  .password-protection {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 60vh;
    padding: 2rem;
  }

  .password-container {
    text-align: center;
    max-width: 400px;
    width: 100%;
    padding: 2rem;
    border-radius: 12px;
    background: var(--card-bg);
    border: 1px solid var(--line-divider);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .lock-icon {
    margin-bottom: 1rem;
    color: var(--primary);
  }

  .password-container h2 {
    margin-bottom: 0.5rem;
    color: rgba(0, 0, 0, 0.85);
    font-size: 1.5rem;
  }

  :global(.dark) .password-container h2 {
    color: rgba(255, 255, 255, 0.85);
  }

  .password-container p {
    margin-bottom: 1.5rem;
    color: rgba(0, 0, 0, 0.75);
    opacity: 0.8;
  }

  :global(.dark) .password-container p {
    color: rgba(255, 255, 255, 0.75);
  }

  .password-input-group {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
  }

  .password-input {
    flex: 1;
    padding: 0.75rem 1rem;
    border: 1px solid var(--line-divider);
    border-radius: 8px;
    background: var(--card-bg);
    color: rgba(0, 0, 0, 0.85);
    font-size: 1rem;
    transition: border-color 0.2s ease;
  }

  :global(.dark) .password-input {
    color: rgba(255, 255, 255, 0.85);
  }

  .password-input::placeholder {
    color: rgba(0, 0, 0, 0.5);
  }

  :global(.dark) .password-input::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }

  .password-input:focus {
    outline: none;
    border-color: var(--primary);
  }

  .unlock-button {
    padding: 0.75rem 1.5rem;
    background: var(--primary);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    cursor: pointer;
    transition: background-color 0.2s ease;
  }

  .unlock-button:hover {
    background: var(--primary-hover, var(--primary));
    opacity: 0.9;
  }

  .unlock-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .error-message {
    color: #ef4444;
    font-size: 0.875rem;
    margin-top: 0.5rem;
  }

  .decrypted-content {
    animation: fadeIn 0.3s ease-in-out;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  /* 移动端适配 */
  @media (max-width: 768px) {
    .password-protection {
      padding: 1rem;
      min-height: 50vh;
    }

    .password-container {
      max-width: none;
      width: 100%;
      padding: 1.5rem;
      margin: 0 0.5rem;
    }

    .password-container h2 {
      font-size: 1.25rem;
      margin-bottom: 0.75rem;
    }

    .password-container p {
      font-size: 0.9rem;
      margin-bottom: 1.25rem;
    }

    .password-input-group {
      flex-direction: column;
      gap: 0.75rem;
    }

    .password-input {
      padding: 0.875rem 1rem;
      font-size: 1rem;
      width: 100%;
    }

    .unlock-button {
      padding: 0.875rem 1rem;
      font-size: 1rem;
      width: 100%;
      white-space: nowrap;
    }

    .error-message {
      font-size: 0.8rem;
      text-align: center;
    }
  }

  /* 小屏手机适配 */
  @media (max-width: 480px) {
    .password-protection {
      padding: 0.75rem;
    }

    .password-container {
      padding: 1.25rem;
      margin: 0 0.25rem;
    }

    .password-container h2 {
      font-size: 1.125rem;
    }

    .password-container p {
      font-size: 0.85rem;
    }

    .password-input {
      padding: 0.75rem 0.875rem;
      font-size: 0.95rem;
    }

    .unlock-button {
      padding: 0.75rem 0.875rem;
      font-size: 0.95rem;
    }
  }
</style>

<script define:vars={{ 
  encryptedContent, 
  passwordHash,
  i18nUnlocking: i18n(I18nKey.passwordUnlocking),
  i18nIncorrect: i18n(I18nKey.passwordIncorrect),
  i18nDecryptError: i18n(I18nKey.passwordDecryptError),
  i18nUnlock: i18n(I18nKey.passwordUnlock)
}}>
  // 导入加密库 - 使用本地文件
  async function loadCryptoLibraries() {
    if (typeof CryptoJS === 'undefined') {
      await new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = '/assets/js/crypto-js.min.js';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    }
    
    if (typeof bcrypt === 'undefined') {
      await new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = '/assets/js/bcrypt.min.js';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    }
  }

  // 加载语法高亮库 - 使用本地文件
  async function loadSyntaxHighlighter() {
    if (typeof hljs === 'undefined') {
      // 加载 highlight.js 核心
      await new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = '/assets/js/highlight.min.js';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
      
      // 加载 highlight.js 样式 - 使用本地文件
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = '/assets/css/highlight-github-dark.min.css';
      document.head.appendChild(link);
      
      // 等待hljs加载完成
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }

  // 为代码块添加样式和功能的函数
  async function enhanceCodeBlocks(container) {
    // 先加载语法高亮库
    await loadSyntaxHighlighter();
    
    const codeBlocks = container.querySelectorAll('pre code');
    
    codeBlocks.forEach(codeElement => {
      const preElement = codeElement.parentElement;
      if (!preElement) return;
      
      // 获取语言信息
      const className = codeElement.className || '';
      const langMatch = className.match(/language-(\w+)/);
      const language = langMatch ? langMatch[1] : '';
      
      // 创建与真正expressive-code完全一致的结构
      const expressiveCodeContainer = document.createElement('div');
      expressiveCodeContainer.className = 'expressive-code';
      
      // 不添加语言标题栏，直接隐藏
      // 加密文章解密后不显示语言标题栏
      
      const frame = document.createElement('div');
      frame.className = 'frame';
      
      // 创建新的pre元素，使用与expressive-code相同的结构
      const newPre = document.createElement('pre');
      newPre.className = 'astro-code';
      newPre.setAttribute('data-language', language || 'text');
      newPre.setAttribute('tabindex', '0');
      newPre.style.backgroundColor = 'var(--codeblock-bg)';
      
      // 加密文章始终显示语言标识（因为没有title栏）
      if (language) {
        frame.classList.add('has-language-badge');
      }
      
      const newCode = document.createElement('code');
      newCode.className = `language-${language || 'text'}`;
      
      // 获取原始代码文本
      const codeText = codeElement.textContent || '';
      
      // 使用 highlight.js 进行语法高亮
      let highlightedCode = codeText;
      if (typeof hljs !== 'undefined') {
        try {
          if (language) {
            // 尝试使用指定语言高亮
            const result = hljs.highlight(codeText, { language: language });
            highlightedCode = result.value;
          } else {
            // 自动检测语言
            const result = hljs.highlightAuto(codeText);
            highlightedCode = result.value;
          }
        } catch (e) {
          console.warn(i18n(I18nKey.syntaxHighlightFailed), e);
          // 如果指定语言失败，尝试自动检测
          try {
            const result = hljs.highlightAuto(codeText);
            highlightedCode = result.value;
          } catch (e2) {
            console.warn(i18n(I18nKey.autoSyntaxHighlightFailed), e2);
            highlightedCode = codeText;
          }
        }
      }
      
      // 将高亮后的代码按行分割并添加行号结构
      const lines = highlightedCode.split('\n');
      
      // 清空原有内容
      newCode.innerHTML = '';
      
      // 设置counter-reset用于行号
      newCode.style.counterReset = 'line';
      
      lines.forEach((line, index) => {
        const lineSpan = document.createElement('span');
        lineSpan.className = 'line';
        lineSpan.innerHTML = line; // 使用innerHTML以保持语法高亮的HTML标签
        
        newCode.appendChild(lineSpan);
        
        // 除了最后一行，都添加换行符
        if (index < lines.length - 1) {
          newCode.appendChild(document.createTextNode('\n'));
        }
      });
      
      newPre.appendChild(newCode);
      
      // 添加复制按钮（使用与expressive-code相同的结构）
      const copyBtn = document.createElement('button');
      copyBtn.className = 'copy-btn';
      copyBtn.setAttribute('aria-label', 'Copy code');
      copyBtn.setAttribute('type', 'button');
      
      const copyBtnIcon = document.createElement('div');
      copyBtnIcon.className = 'copy-btn-icon';
      
      // 复制图标SVG
      const copyIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      copyIcon.setAttribute('viewBox', '0 -960 960 960');
      copyIcon.setAttribute('class', 'copy-btn-icon copy-icon');
      const copyPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      copyPath.setAttribute('d', 'M368.37-237.37q-34.48 0-58.74-24.26-24.26-24.26-24.26-58.74v-474.26q0-34.48 24.26-58.74 24.26-24.26 58.74-24.26h378.26q34.48 0 58.74 24.26 24.26 24.26 24.26 58.74v474.26q0 34.48-24.26 58.74-24.26 24.26-58.74 24.26H368.37Zm0-83h378.26v-474.26H368.37v474.26Zm-155 238q-34.48 0-58.74-24.26-24.26-24.26-24.26-58.74v-557.26h83v557.26h461.26v83H213.37Z');
      copyIcon.appendChild(copyPath);
      
      // 成功图标SVG
      const successIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
      successIcon.setAttribute('viewBox', '0 -960 960 960');
      successIcon.setAttribute('class', 'copy-btn-icon success-icon');
      const successPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      successPath.setAttribute('d', 'm389-377.13 294.7-294.7q12.58-12.67 29.52-12.67 16.93 0 29.61 12.67 12.67 12.68 12.67 29.53 0 16.86-12.28 29.14L419.07-288.41q-12.59 12.67-29.52 12.67-16.94 0-29.62-12.67L217.41-430.93q-12.67-12.68-12.79-29.45-.12-16.77 12.55-29.45 12.68-12.67 29.62-12.67 16.93 0 29.28 12.67L389-377.13Z');
      successIcon.appendChild(successPath);
      
      copyBtnIcon.appendChild(copyIcon);
      copyBtnIcon.appendChild(successIcon);
      copyBtn.appendChild(copyBtnIcon);
      
      // 复制功能 - 使用与Markdown.astro相同的逻辑
      copyBtn.addEventListener('click', async () => {
        try {
          // 获取所有.line元素的文本内容（不包括行号）
          const codeElements = newCode.querySelectorAll('.line');
          const code = Array.from(codeElements)
            .map(el => el.textContent)
            .map(t => t === '\n' ? '' : t)
            .join('\n');
          
          await navigator.clipboard.writeText(code);
          copyBtn.classList.add('success');
          
          // 清除之前的timeout
          const timeoutId = copyBtn.getAttribute('data-timeout-id');
          if (timeoutId) {
            clearTimeout(parseInt(timeoutId));
          }
          
          // 设置新的timeout
          const newTimeoutId = setTimeout(() => {
            copyBtn.classList.remove('success');
          }, 1000);
          
          copyBtn.setAttribute('data-timeout-id', newTimeoutId.toString());
        } catch (err) {
          console.error(i18n(I18nKey.copyFailed), err);
        }
      });
      
      frame.appendChild(newPre);
      frame.appendChild(copyBtn);
      expressiveCodeContainer.appendChild(frame);
      
      // 替换原始pre元素
      preElement.parentNode.replaceChild(expressiveCodeContainer, preElement);
    });
  }

  // 为标题添加id和锚点链接的函数
  function addHeadingAnchors(container) {
    const headings = container.querySelectorAll('h1, h2, h3, h4, h5, h6');
    const usedIds = new Set();
    
    headings.forEach(heading => {
      // 生成slug id（模拟rehype-slug功能）
      let slug = heading.textContent
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '') // 移除特殊字符
        .replace(/[\s_-]+/g, '-') // 替换空格和下划线为连字符
        .replace(/^-+|-+$/g, ''); // 移除开头和结尾的连字符
      
      // 确保id唯一
      let uniqueSlug = slug;
      let counter = 1;
      while (usedIds.has(uniqueSlug)) {
        uniqueSlug = `${slug}-${counter}`;
        counter++;
      }
      usedIds.add(uniqueSlug);
      
      // 设置id
      heading.id = uniqueSlug;
      
      // 添加锚点链接（模拟rehype-autolink-headings功能）
      const anchor = document.createElement('span');
      anchor.className = 'anchor-icon';
      anchor.setAttribute('data-pagefind-ignore', 'true');
      anchor.textContent = '#';
      
      const anchorWrapper = document.createElement('a');
      anchorWrapper.className = 'anchor';
      anchorWrapper.href = `#${uniqueSlug}`;
      anchorWrapper.appendChild(anchor);
      
      // 将锚点添加到标题末尾
      heading.appendChild(anchorWrapper);
    });
  }

  async function renderMarkdownContent(markdownText) {
    // 加载marked库用于markdown渲染 - 使用本地文件
    if (typeof marked === 'undefined') {
      await new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = '/assets/js/marked.min.js';
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    }
    
    // 配置marked的基本选项
    marked.setOptions({
      breaks: true,
      gfm: true
    });
    
    const contentDiv = document.getElementById('decrypted-content');
    const htmlContent = marked.parse(markdownText);
    
    // 创建与正常文章完全相同的结构
    const markdownWrapper = document.createElement('div');
    markdownWrapper.className = 'prose dark:prose-invert prose-base !max-w-none custom-md mb-6 markdown-content onload-animation';
    markdownWrapper.setAttribute('data-pagefind-body', '');
    markdownWrapper.innerHTML = htmlContent;
    
    // 为标题添加id和锚点链接（模拟rehype-slug和rehype-autolink-headings插件功能）
    addHeadingAnchors(markdownWrapper);
    
    // 为代码块添加样式和功能（异步）
    await enhanceCodeBlocks(markdownWrapper);
    
    // 清空容器并添加新内容
    contentDiv.innerHTML = '';
    contentDiv.appendChild(markdownWrapper);
    
    // 重置contentDiv的样式，让它作为普通容器
    contentDiv.className = '';
    contentDiv.style.cssText = '';
    
    // 触发TOC更新
    const tocElement = document.querySelector('table-of-contents');
    if (tocElement && typeof tocElement.regenerateTOC === 'function') {
      // 等待DOM更新后重新生成TOC
      setTimeout(() => {
        tocElement.regenerateTOC();
        tocElement.init();
      }, 100);
    }
    
    // 触发移动端TOC更新
    if (typeof window.mobileTOCInit === 'function') {
      setTimeout(() => {
        window.mobileTOCInit();
      }, 150);
    }
    
    // 触发动画结束事件，让TOC知道动画完成
    const animationEndEvent = new Event('animationend');
    markdownWrapper.dispatchEvent(animationEndEvent);
  }

  async function initPasswordProtection() {
    await loadCryptoLibraries();
    
    const passwordInput = document.getElementById('password-input');
    const unlockBtn = document.getElementById('unlock-btn');
    const errorMessage = document.getElementById('error-message');
    const protectionDiv = document.getElementById('password-protection');
    const contentDiv = document.getElementById('decrypted-content');

    async function attemptUnlock() {
      const inputPassword = passwordInput.value.trim();
      
      if (!inputPassword) {
        showError(i18n(I18nKey.passwordRequired));
        return;
      }

      unlockBtn.disabled = true;
      unlockBtn.textContent = i18nUnlocking;
      errorMessage.style.display = 'none';

      try {
        // 验证密码
        const isPasswordCorrect = bcrypt.compareSync(inputPassword, passwordHash);
        
        if (!isPasswordCorrect) {
          showError(i18nIncorrect);
          return;
        }

        // 解密内容
        const decryptedBytes = CryptoJS.AES.decrypt(encryptedContent, inputPassword);
        const decryptedContent = decryptedBytes.toString(CryptoJS.enc.Utf8);
        
        if (!decryptedContent) {
          showError(i18nDecryptError);
          return;
        }

        // 渲染markdown内容
        await renderMarkdownContent(decryptedContent);
        protectionDiv.style.display = 'none';
        contentDiv.style.display = 'block';
        
        // 保存解锁状态到sessionStorage（可选）
        sessionStorage.setItem('page-unlocked-' + window.location.pathname, 'true');
        
      } catch (error) {
        console.error(i18n(I18nKey.decryptionError), error);
        showError(i18n(I18nKey.passwordDecryptRetry));
      } finally {
        unlockBtn.disabled = false;
        unlockBtn.textContent = i18nUnlock;
      }
    }

    function showError(message) {
      errorMessage.textContent = message;
      errorMessage.style.display = 'block';
      passwordInput.focus();
    }

    // 事件监听
    unlockBtn.addEventListener('click', attemptUnlock);
    passwordInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        attemptUnlock();
      }
    });

    // 检查是否已经解锁过（可选功能）
    if (sessionStorage.getItem('page-unlocked-' + window.location.pathname) === 'true') {
      passwordInput.value = 'auto-unlock';
      // 这里可以添加自动解锁逻辑，但需要存储密码，不太安全
    }

    // 聚焦到密码输入框
    passwordInput.focus();
  }

  // 页面加载完成后初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initPasswordProtection);
  } else {
    initPasswordProtection();
  }
</script>